package com.guqj.nio.netty.ex;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;


public class TimeServer {

	public void bind(int port) throws InterruptedException {
		// 服务器线程组 用于网络事件的处理 一个用于服务器接收客户端的连接
		// 另一个线程组用于处理SocketChannel的网络读写
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup wokerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(bossGroup, wokerGroup).channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 1024)
					.childHandler(new ChildChannelHandler());
			
			// 绑定端口，同步等待更新
			Channel f = serverBootstrap.bind(port).sync().channel();
			System.out.println("timeServer启动。。。。。。。。");
			// 等待服务端监听端口关闭
			f.closeFuture().sync();
		} finally {
			// 退出，释放线程资源
			bossGroup.shutdownGracefully();
			wokerGroup.shutdownGracefully();
		}
	}
	
	/*
	 * <p>
	 * 	作用是当创建NioServerSocketChannel成功后，
	 * 	在初始化的时候将它的ChannelHandler设置到ChannelPiepeline中，用于处理网络I/O事件
	 * </p>
	 */
	class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			ch.pipeline().addLast("handler", new TimeServerHandler());
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		new TimeServer().bind(11001);
	}
}
